package com.hnevc.androiduiclassone8;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class QQSave extends AppCompatActivity {
    EditText mETNumber, mETPassword;
    Button mBTnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qqsave);
        initView();
        initEvent();
    }

    private void initEvent() {
        mBTnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = mETNumber.getText().toString().trim();
                String password = mETPassword.getText().toString().trim();

                saveUserInfo(username, password);

            }
        });
    }

    private void saveUserInfo(String username, String password) {
        String data = username+":"+ password;
        try {
            FileOutputStream fos = openFileOutput("data.txt",MODE_PRIVATE);
            fos.write(data.getBytes());
            fos.close();
            Toast.makeText(QQSave.this,"保存成功",Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    private Map<String,String> getUserInfo() {
        try {
            FileInputStream fis = openFileInput("data.txt");
            byte[] bytes = new byte[fis.available()];
            fis.read();
            fis.close();
            String temp = new String(bytes);
            String[] strs = temp.split(":");
            Map<String, String> map = new HashMap();
            map.put("username", strs[0]);
            map.put("password", strs[1]);
            return map;
        } catch (FileNotFoundException e) {
            return null;


        } catch (Exception e) {
            return null;
        }
    }

    private void initView() {
        mETNumber = findViewById(R.id.et_number);
        mETPassword= findViewById(  R.id.et_password);
        mBTnLogin = findViewById(R.id.btn_login);
        Map<String, String> userInfo = getUserInfo();
        if(userInfo !=null){
            mETNumber.setText(userInfo.get("username"));
            mETPassword.setText(userInfo.get("password"));
        }
    }

}
